import { asyncRouterMap,constantRouterMap } from '@/router';
import { getRightCodeListByToken } from '@/api/user';
//import Cookies from 'js-cookie';


function hasPermission(rightlist, route) {
  if (route.meta && route.meta.right) {
    return rightlist.indexOf(route.meta.right)>=0
  } else {
    return true
  }
}

function filterAsyncRouter(asyncRouterMap, rightlist) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(rightlist, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, rightlist)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        getRightCodeListByToken().then(response => {
          if (response.code==0){           
            let rightlist = response.data;
            let accessedRouters
            accessedRouters = filterAsyncRouter(asyncRouterMap, rightlist)
            commit('SET_ROUTERS', accessedRouters)
            resolve(); 
          }
        });
      });
    }
  },
  computed: {
    routes: function () {
      //this.$router.addRoutes(state.routers);  
    }
  },

}
export default permission